package com.pai4j.ugc.service.chain;
import com.pai4j.domain.vo.response.moment.MomentMediaVO;
import com.pai4j.domain.vo.response.moment.MomentVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;


/**
 * 提取朋友圈图片媒体资源的宽高尺寸等基础信息
 */
@Slf4j
@Component
public class MomentImageHandler implements MomentPublishHandler {


    @Override
    public void handle(MomentVO moment, MomentPublishHandlerChain chain) throws Exception {
        if (!ObjectUtils.equals(moment.getIncludeImages(), true)) {
            chain.handle(moment, chain);
            return;
        }
        List<MomentMediaVO> images = moment.getImages();
        for (MomentMediaVO image : images) {
            this.doHandleImage(image);
        }
        chain.handle(moment, chain);
    }

    /**
     * 提取网络图片资源宽高、大小等信息
     *
     * @param imageVO
     */
    private void doHandleImage(MomentMediaVO imageVO) {
        try {
            URL url = new URL(imageVO.getResource());
            BufferedImage image = ImageIO.read(url.openStream());
            if (image != null) {
                imageVO.setWidth(image.getWidth());
                imageVO.setHeight(image.getHeight());
            }
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("HEAD");
            long size = conn.getContentLengthLong();
            imageVO.setSize(size);
        } catch (Exception e) {
            log.error("doHandleImage error", e);
        }
    }
}
